################################################################
s=r'''

                                          _oo0oo_
                                         o8888888o
                                         88" . "88
                                         (| -_- |)
                                         0\  =  /0
                                       ___/`---'\___
                                     .' \\|     |// '.
                                    / \\|||  :  |||// \
                                   / _||||| -:- |||||- \
                                  |   | \\\  -  /// |   |
                                  | \_|  ''\---/''  |_/ |
                                  \  .-\__  '-'  ___/-. /
                                ___'. .'  /--.--\  `. .'___
                             ."" '<  `.___\_<|>_/___.' >' "".
                            | | :  `- \`.;`\ _ /`;.`/ - ` : | |
                            \  \ `_.   \_ __\ /__ _/   .-` /  /
                        =====`-.____`.___ \_____/___.-`___.-'=====
                                          `=---='
                        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
                                佛祖保佑            永无BUG
                                你已经击败全国99.99%的程序员
'''
print(s)
################################################################

import csv
import os
import random
import sys
import traceback

deps = ['guizero','imageio']
print(f'需要的依赖有：{deps}\n如果启动报错，请手动安装。')
for dep in deps:
    print(f'{dep}安装方法：')
    print(
        f'\n\tpython3 -m pip install {dep} -U -i https://pypi.tuna.tsinghua.edu.cn/simple\n')

import guizero

class MyAPP:
    'APP框架'

    def __init__(self):
        '初始化'
        self.app = guizero.App('我的程序', width=800, height=568, bg='white')
        self.path = os.path.dirname(os.path.abspath(__file__))
        self.setupPath = os.path.join(self.path, 'setup.csv')
        self.filePath = None
        self.settings = self.loadsettings()
        self.app.when_closed = self.close
        self.draw()

    def draw(self):
        '绘制程序所有的组件'
        tk = self.app.tk
        tk.maxsize(800, 568)
        # 下方代码是建立顶部工具栏
        options = [
            [['打开', self.selectFile], ['设置', self.setup], ['关闭窗口', self.close]],
            [['撤销', self.undo], ['重做', self.redo], ['复制', self.copy], ['粘贴', self.paste]],
            [['关于', self.info], ['联系方式', self.contact]]
        ]
        self.menuBar = guizero.MenuBar(self.app,
                                        toplevel=['文件', '编辑', '帮助'],
                                        options=options)
        guizero.Box(self.app, width='fill', height=1, border=1)
        self.drawMyApps()

    def selectFile(self):
        '选择文件'
        self.filePath = guizero.select_file(title='请选择文件：', save=False)

    def setup(self):
        '点击设置按钮'
        newWindow = guizero.Window(self.app, title='设置')
        newWindow.tk.maxsize(500, 500)
        guizero.Text(newWindow, '设置页面', size=30, color='#ff88ff', align='top')
        self.guiSettingBox = guizero.Box(
            newWindow, layout='grid', align='top')
        self.flushSettings(newWindow)

        def onClose():
            self.saveSettings()
            newWindow.destroy()
        newWindow.when_closed = onClose

    def close(self):
        self.setupPath = os.path.join(self.path, 'setup.csv')
        try:
            self.saveSettings()
        except AttributeError:
            print('设置未变更，所以不用保存。')
        finally:
            self.app.destroy()

    def loadsettings(self):
        '加载配置文件'
        if os.path.isfile(self.setupPath):
            settings = self.readCsv()
        else:
            settings = [
                ['标题', '', '词云'],
                ['是否XXX', '是,否', '是'],
            ]
            self.writeCsv(settings)
        self.app.title = settings[0][2]
        return settings

    def saveSettings(self):
        '保存配置文件'
        children = self.guiSettingBox.children
        for i in range(len(self.settings)):
            self.settings[i][2] = children[2*i+1].value
        self.writeCsv(self.settings)

    def flushSettings(self, master):
        '刷新配置'
        self.guiSettingBox.destroy()
        self.guiSettingBox = guizero.Box(
            master, layout='grid', align='top')
        words = '0123456789ab'
        count = 0
        for setting in self.settings:
            color = '#'+''.join(random.sample(words, 6))
            print(color)
            guizero.Text(self.guiSettingBox, text=setting[0], grid=[
                         0, count], color=color)
            if setting[1]:
                nowSetting = setting[1].split(',')
                print(setting[1])
                guizero.ButtonGroup(self.guiSettingBox, options=nowSetting, grid=[
                                    1, count], selected=setting[2], horizontal=True)
            else:
                guizero.TextBox(self.guiSettingBox,
                                text=setting[2], width=10, grid=[1, count])
            count += 1

    def readCsv(self):
        '读取csv文件'
        settings=[]
        with open(self.setupPath,'r',encoding='utf-8') as f:
            reader=csv.reader(f)#建立读取器
            for row in reader:
                if len(row)==3:
                    settings.append(row)
        return settings[1:]

    def writeCsv(self, settings):
        '写入csv设置文件'
        if os.path.isfile(self.setupPath):#检查配置文件是否存在
            os.remove(self.setupPath)#删掉配置文件
        with open(self.setupPath,'w',encoding='utf-8') as f:
            writer=csv.writer(f)#建立写入器
            writer.writerow(['名称','选项','值'])
            for setting in settings:
                writer.writerow(setting)#写入当前拿到的设置项

        
    def drawMyApps(self):
        '这里绘制你要用的模块'

    def copy(self):
        '复制'

    def paste(self):
        '粘贴'

    def undo(self):
        '撤销'

    def redo(self):
        '重做'

    def info(self):
        '关于'

    def contact(self):
        '联系'

    def display(self):
        '显示主界面'
        self.app.display()


if __name__ == "__main__":
    if 'wordcloud' in dir() and 'guizero' in dir():
        app = MyAPP()
        app.display()
    else:
        print('词云库和guizero库导入失败，请在终端中运行下面代码手动安装：')
        print('\n\tpython3 -m pip install wordcloud guizero jieba -U -i https://pypi.tuna.tsinghua.edu.cn/simple')
